package cn.yhp.chatgpt.data.trigger.http;

import cn.yhp.chatgpt.data.domain.auth.model.entity.AuthStateEntity;
import cn.yhp.chatgpt.data.domain.auth.model.valobj.AuthTypeVO;
import cn.yhp.chatgpt.data.domain.auth.service.IAuthService;
import cn.yhp.chatgpt.data.types.common.Constants;
import cn.yhp.chatgpt.data.types.model.Response;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Slf4j
@RestController()
@RequestMapping("/api/${app.config.api-version}/auth/")
public class AuthController {

    @Resource
    private IAuthService authService;

    @PostMapping("login")
    public Response<String> doLogin(@RequestParam String code) {
        log.info("鉴权登录校验开始，验证码: {}", code);
        AuthStateEntity authStateEntity = authService.doLogin(code);
        log.info("鉴权登录校验完成，验证码: {} 结果: {}", code, JSON.toJSONString(authStateEntity));
        // 拦截，鉴权失败
        if (!AuthTypeVO.A0000.getCode().equals(authStateEntity.getCode())) {
            return Response.<String>builder()
                    .code(Constants.ResponseCode.TOKEN_ERROR.getCode())
                    .info(Constants.ResponseCode.TOKEN_ERROR.getInfo())
                    .build();
        }
        // 放行，鉴权成功(返回token)
        return Response.<String>builder()
                .code(Constants.ResponseCode.SUCCESS.getCode())
                .info(Constants.ResponseCode.SUCCESS.getInfo())
                .data(authStateEntity.getToken())
                .build();
    }
}